package cn.tedu.csmall.stock.webapi.controller;

import cn.tedu.csmall.commons.exception.CoolSharkServiceException;
import cn.tedu.csmall.commons.pojo.stock.dto.StockReduceCountDTO;
import cn.tedu.csmall.commons.restful.JsonResult;
import cn.tedu.csmall.commons.restful.ResponseCode;
import cn.tedu.csmall.stock.service.IStockService;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.json.Json;

@Api(tags = "库存管理模块")
@RestController
@Slf4j
@RequestMapping("/base/stock")
public class StockController {

    @Autowired
    private IStockService stockService;

    @PostMapping("/reduce/count")
    @ApiOperation("减少库存数")
    //@SentinelResource注解需要标记在控制层方法上，在方法第一次运行后
    //就会被sentinel仪表台检测
    //该方法在运行前不会出现在仪表台中
    //blockHandler 可以设置当前控制器方法被限流时，要运行的自定义限流方法
    @SentinelResource(value = "减少库存数",
                      blockHandler = "blockError",
                      fallback = "fallbackError")
    public JsonResult reduceCommodityCount(StockReduceCountDTO stockReduceCountDTO){

        //调用业务逻辑层
        stockService.reduceCommodityCount(stockReduceCountDTO);
        //随即发生异常，测试自定义降级方法效果
        if (Math.random()<0.5){
            throw new CoolSharkServiceException(
                    ResponseCode.INTERNAL_SERVER_ERROR,"发生随机异常"
            );
        }
        return JsonResult.ok("库存减少完成");

    }

    public JsonResult blockError(StockReduceCountDTO stockReduceCountDTO,
                                 BlockException e){
        //这个方法表示当前请求被限流了，返回提示即可
        log.info("服务器忙");
        return JsonResult.failed(ResponseCode.INTERNAL_SERVER_ERROR,"服务器忙,请稍后再试");
    }
    //自定义降级方法 由@SentinelResource的 fallback属性指定
    public JsonResult fallbackError(StockReduceCountDTO stockReduceCountDTO,
                                    Throwable throwable){
        //输出异常信息
        throwable.printStackTrace();
        //返回降级
        return JsonResult.failed(ResponseCode.INTERNAL_SERVER_ERROR,"服务降级");

    }

}
